package example;

public class Exercise002 {

    int calculate(String message) {
        if (message.contains("$")) {
            String[] dollarArray = message.split("\\$");
            int first = getDollarValue(dollarArray[0]);
            for (int i = 0; i < dollarArray.length - 1; i++) {
                int second = getDollarValue(dollarArray[i + 1]);
                first = 3 * first + 2 * second + 1;
            }
            return first;
        } else {
            return getAtValue(message);
        }
    }


    private int getDollarValue(String message) {
        if (message.contains("@")) {
            return getAtValue(message);
        } else {
            return Integer.parseInt(message);
        }
    }

    private int getAtValue(String message) {
        String[] atArray = message.split("@");
        int firstAt = Integer.parseInt(atArray[0]);
        for (int j = 0; j < atArray.length - 1; j++) {
            int secondAt = Integer.parseInt(atArray[j + 1]);
            firstAt = 2 * firstAt + secondAt + 3;
        }
        return firstAt;
    }

    public static void main(String[] args) {
        Exercise002 exercise002 = new Exercise002();
        int calculate = exercise002.calculate("11@2$3@14");
        System.out.printf("calculate:%d\n",calculate);

        int calculate2 = exercise002.calculate("103$104@105@2$106@107");
        System.out.printf("calculate:%d\n",calculate2);

        int calculate3 = exercise002.calculate("4@5");
        System.out.printf("calculate:%d\n", calculate3);
    }
}
